package com.gxa.service.impl;

import com.alibaba.fastjson.JSON;

import com.gxa.config.RabbitConfig;
import com.gxa.constantvar.ResultEnum;
import com.gxa.dto.MsgDTO;
import com.gxa.endpoint.WebSocketEndPoint;
import com.gxa.service.SendMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@Slf4j
public class SendMessageServiceImpl implements SendMessageService {


    final AmqpTemplate amqpTemplate;

    public SendMessageServiceImpl(AmqpTemplate amqpTemplate) {
        this.amqpTemplate = amqpTemplate;
    }


    @Override
    public String send(MsgDTO msgDTO) {
        String message = msgDTO.getMsg();
        //字符串不为空 切长度大于0 返回true
        if (StringUtils.hasText(message)) {
            String msg = JSON.toJSONString(msgDTO);
            msg = msg.replace("\\t", "").replace("\\n", "");
            amqpTemplate.convertAndSend(RabbitConfig.FANOUT_EXCHANGE, "", msg);
            return ResultEnum.SEND_SUCCESS.getTitle();
        }
        return ResultEnum.SEND_NULL.getTitle();
    }

    /**
     * @param msgDTO 实体类
     */
    @Override
    public void sendToUser(MsgDTO msgDTO) {
        List<String> persons = msgDTO.getPersons();
        String message = msgDTO.getMsg();
        if (!StringUtils.hasText(message)) {
            return;
        }
        if (ObjectUtils.isEmpty(persons)) {
            WebSocketEndPoint.batchSend(message);
            return;
        }
        WebSocketEndPoint.sendToUser(persons, message);
    }
}


